package com.zs.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.zs.protocol.Protocol;
import com.zs.protocol.TCPProtocol;

public class ChatServer {

	private ServerSocketChannel  channel;
	private ExecutorService servicePool;
	private Selector selector;
	private Protocol protocol;
	public ChatServer() {
		try {
			protocol=new TCPProtocol();
			selector=Selector.open();
			//ServerSocketChannel 接受入站连接，你无法读取，写入或连接  待客户端连接以后需要调用accept方法 获得一个新的通道
			
			channel=ServerSocketChannel.open().bind(new InetSocketAddress(8090));
			channel.configureBlocking(false);
			channel.register(selector,SelectionKey.OP_ACCEPT);
			System.out.println("channel 1:"+channel.hashCode());
			servicePool=Executors.newSingleThreadExecutor();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void start(){
		servicePool.execute(new recevieTherad());
	}
	
	
	class recevieTherad implements Runnable{

		@Override
		public void run() {
			try {
				while(true){
					
					if(selector.select()==0){
						continue;
					}
					Set<SelectionKey> keys=selector.selectedKeys();
					Iterator<SelectionKey> itor=keys.iterator();
					while(itor.hasNext()){
						SelectionKey key=itor.next();
						if(key.isAcceptable()){
							protocol.handleAccept(key);
							
						}else if(key.isReadable()){
							protocol.handleRead(key);
							
						}else if(key.isWritable()){
							protocol.handleWrite(key);
						}
						itor.remove();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	
}
